﻿using Cube.ImportAccount.DataBase;
using Cube.ImportAccount.Mapping;
using Cube.ImportAccount.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Cube.ImportAccount
{
    public partial class ImportForm : Form
    {
        private DbHelper dbHelper { get; set; }

        public ImportForm()
        {
            InitializeComponent();
        }

        private void ImportForm_Load(object sender, EventArgs e)
        {
            dbHelper = new DbHelper();
        }

        private void ImportForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (dbHelper != null)
            {
                dbHelper.Close();
            }
        }

        private void selectFileButton_Click(object sender, EventArgs e)
        {
            DialogResult dr = openExcelFileDialog.ShowDialog();
        }

        private void openFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            string fileName = openExcelFileDialog.FileName;
            showFilePathText.Text = fileName;
            if (!string.IsNullOrEmpty(fileName))
            {
                string ext = fileName.Substring(fileName.LastIndexOf("."));
                if (!(ext == ".xls" || ext == ".xlsx"))
                {
                    openExcelFileDialog.FileName = string.Empty;
                    MessageBox.Show("请选择Excel文件导入", "错误");
                }
            }
        }

        private void importButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(openExcelFileDialog.FileName)) {
                MessageBox.Show("请选择Excel文件导入", "错误");
                return;
            }

            // 禁用按键
            importButton.Enabled = false;

            // 读取要注册的用户名和手机号码
            DataTable dt = ExcelUtil.ExcelToTable(openExcelFileDialog.FileName);
            List<Dictionary<string, string>> dics = new List<Dictionary<string, string>>();
            if (dt != null)
            {
                foreach(DataRow dr in dt.Rows)
                {
                    Dictionary<string, string> item = new Dictionary<string, string>();
                    item.Add("username", dr[0].ToString());
                    item.Add("mobile", dr[1].ToString());
                    dics.Add(item);
                }
            }
            
            // 清空执行结果
            outputResult.Text = string.Empty;

            if (dics.Count > 0)
            {
                List<string> userNames = dics.Select(n => n["username"]).ToList();
                List<string> mobiles = dics.Select(n => n["mobile"]).ToList();
                List<UserEntity> entities = dbHelper.FindList<UserEntity>(n => 
                    userNames.Contains(n.UserName) || mobiles.Contains(n.MobilePhone)).ToList();
                foreach (UserEntity user in entities)
                {
                    Dictionary<string, string> delObj = dics.Single(n => n["username"] == user.UserName || n["mobile"] == user.MobilePhone);
                    if (delObj != null)
                    {
                        dics.Remove(delObj);
                    }
                    outputResult.AppendText(string.Format("Error: {0},{1} 账号已存在\r\n", user.UserName, user.MobilePhone));
                }

                entities = new List<UserEntity>();
                foreach (Dictionary<string, string> target in dics)
                {
                    UserEntity entity = new UserEntity()
                    {
                        Id = Guid.NewGuid().ToString(),
                        UserName = target["username"],
                        PassWord = string.Empty,
                        MobilePhone = target["mobile"],
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    };
                    entities.Add(entity);
                }

                if (entities.Count > 0)
                {
                    int cnt = dbHelper.Insert(entities);
                    if (cnt > 0)
                    {
                        outputResult.AppendText("OK: 账号导入成功！");
                    }
                }
            }

            // 开启按键
            importButton.Enabled = true;
            openExcelFileDialog.FileName = string.Empty;
        }
    }
}
